import { type OptionalFields } from '@gnlab/utils'
import { Form, Input, Button, message } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import { WordsInput } from '@/desktop/components/words'
import services from '@/services'
import { WordType } from '@/services/common/definition'
import {
  type WelcomeMessage,
  type BaseWelcomeMessage,
  getEmptyWelcomeMessage,
} from '@/services/features/welcome-messages'
import MatchTypeFields from './match-type'
import './index.module.less'

export interface EditingMessage extends BaseWelcomeMessage {
  id?: number
}

export const labelCol = { span: 6 }

export default function MessageEditModal(props: {
  editing: false | true | WelcomeMessage
  onFinish: () => void
}) {
  const { editing, onFinish } = props

  const title = editing !== false ? (editing === true ? '新建增强欢迎语' : '编辑增强欢迎语') : ''

  return <ImportantEditModal
    title={title}
    width="800px"
    styleName="modal"
    open={editing !== false}
    onCancel={onFinish}
  >
    {editing !== false ? <Content editing={editing} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

function Content(props: { editing: true | WelcomeMessage; onFinish: () => void }) {
  const { editing, onFinish } = props
  const initialMessage = useMemo(
    () => (editing === true ? getEmptyWelcomeMessage() : editing),
    [editing],
  )

  const [saving, setSaving] = useState(false)
  const onSave = useCallback(
    async (values: OptionalFields<WelcomeMessage, 'id' | 'keyword' | 'appid' | 'enterpoint'>) => {
      setSaving(true)
      const res = await services.features.welcomeMessages.addOrUpdate({
        ...values,
        keyword: values.keyword ?? null,
        appid: values.appid ?? null,
        enterpoint: values.enterpoint ?? null,
      })
      setSaving(false)

      if (res.success) {
        void message.success(`增强欢迎语${editing === true ? '创建' : '修改'}成功`)
        onFinish()
      } else {
        void message.warning(res.error)
      }
    },
    [editing, onFinish],
  )

  return <Form
    initialValues={initialMessage}
    labelCol={labelCol}
    requiredMark={false}
    onFinish={onSave}
  >
    <main>
      <Form.Item hidden name="id">
        <Input />
      </Form.Item>
      <Form.Item hidden name="enable">
        <Input />
      </Form.Item>

      <Form.Item name="name" label="欢迎语名称" rules={[{ required: true }]}>
        <Input maxLength={50} />
      </Form.Item>

      <MatchTypeFields />

      <Form.Item name="words" label="设置增强欢迎语" rules={[{ required: true }]}>
        <WordsInput extraTypes={[WordType.GroupInvite]} />
      </Form.Item>
    </main>

    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit" loading={saving}>
        保存
      </Button>
    </footer>
  </Form>
}
